package com.cloudDemoOrder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudDemoOrder.dao.OrderQueryDao;
import com.cloudDemoOrder.service.OrderService;
import com.cloudDemoOrder.service.ProductFeignService;
import com.cloudDemoOrder.service.UserFeignService;
import entity.Order;
import entity.Product;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Daft_V
 * @date 2022/5/6 9:58
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderQueryDao orderQueryDao;
    @Autowired
    UserFeignService userFeignService;
    @Autowired
    ProductFeignService productFeignService;


    @Override
    public List<Order> orderList() {
        return orderQueryDao.list();
    }

    @Override
    public Order queryOrderById(int id) {
        Order order = orderQueryDao.getById(id);
        return order;
    }

    @Override
    public JSONObject insertOrder(int uid, int pid, int number) {
        Order order = new Order();
        Map<String, Object> message = new HashMap<>();

        //查询用户信息
        User user=userFeignService.queryUserById(uid);

        //更新库存数量
        Boolean updateFlag=productFeignService.updateStock(pid, number);

        //获取商品信息
        Product product = productFeignService.queryProductById(pid);

        //提交数量小于1或者库存不足
        if (!updateFlag) {
            message.put("code", 500);
            message.put("msg", "库存不足或提交数量有误");
        }

        order.setUid(user.getUid());
        order.setUsername(user.getUsername());
        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(number);

        //总价格
        Double price = product.getPprice() * number;

        try {
            if(updateFlag){
                orderQueryDao.getBaseMapper().insert(order);
                message.put("code", 200);
                message.put("data", order);
                message.put("msg", "insert order success");
                message.put("price", price);
            }else{
                message.put("code", 500);
                message.put("msg", "库存不足或提交数量有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            message.put("code", 500);
            message.put("msg", "insert order error");
        }
        JSONObject jsonObject = new JSONObject(message);
        return jsonObject;
    }
}
